﻿#include "uimodelmanage.h"

#include <QPushButton>
#include <QHBoxLayout>
#include <QListView>
#include <QScrollBar>
#include <QStandardItemModel>
#include <QJsonArray>
#include <QLabel>
#include <QSharedPointer>
#include <QFrame>
#include <QPoint>
#include <QCursor>
#include <QPainter>

#include <shlib/csigmanager.h>
#include <shlib/cwebrequestapi.h>
#include <shlib/viewmodel/ctablemodel.h>
#include <shlib/viewmodel/imodel.h>
#include <shlib/quc_sdk/iconhelper/icon_helper.h>
#include <shlib/quc_sdk/customwidget/uicustomdialog.h>

#include "model/uimodelmanagedelegate.h"
#include "model/uimodelinfo.h"

UiModelManage::UiModelManage(QWidget *parent) :
    QWidget(parent)
{
    initUi();
    initData();
}

UiModelManage::~UiModelManage()
{

}

void UiModelManage::addSceneItem(QSharedPointer<IModel> &model)
{

}

void UiModelManage::removeSceneItem(QString name)
{

}

QStandardItemModel *UiModelManage::getModel() const
{

}

void UiModelManage::setModel(QStandardItemModel *model)
{

}

void UiModelManage::slotNewScene()
{

}

void UiModelManage::slotRemoveScene(QString name)
{

}

void UiModelManage::slotEditScene(QString name)
{

}

void UiModelManage::slotCopyScene(QString name)
{

}

void UiModelManage::importModel()
{
    UiCustomDialog dialog;
    dialog.resize(400, 250);
    QLabel lab("nihao o");
    dialog.setConten(&lab);
    while (dialog.exec() == QDialog::Accepted) {
        qDebug() << lab.text();
        break;
    }
}

void UiModelManage::initUi()
{
    IconHelper* iconsMgr = IconHelper::instance();

    QFrame* farme = new QFrame(this);

    m_newSceneBtn = new QPushButton("新建模型",farme);
    m_newSceneBtn->setObjectName("scene_manager_btn");
    m_newSceneBtn->setMinimumSize(90, 25);
    m_newSceneBtn->setStyleSheet("QPushButton { background-color: #1e3050; border: none; border-radius: 6px; color: white;}");
    m_newSceneBtn->setIconSize(QSize(25,25));
    m_newSceneBtn->setIcon(QIcon(iconsMgr->getPixmap(QColor::fromString("#63E6BE"), IconHelper::FontAwesome6Solid, 0xf5ff, 22, 25,25)));
    connect(m_newSceneBtn,&QPushButton::clicked,this,&UiModelManage::slotNewScene);

    m_importModelBtn = new QPushButton("导入模型",farme);
    m_importModelBtn->setObjectName("import_model_btn");
    m_importModelBtn->setMinimumSize(90, 25);
    m_importModelBtn->setStyleSheet("QPushButton { background-color: #1e3050; border: none; border-radius: 6px; color: white;}");
    m_importModelBtn->setIconSize(QSize(25,25));
    m_importModelBtn->setIcon(QIcon(iconsMgr->getPixmap(QColor::fromString("#63E6BE"), IconHelper::FontAwesome6Solid, 0xf07c, 19, 25,25)));
    connect(m_importModelBtn, &QPushButton::clicked, this, &UiModelManage::importModel);


    m_refreshSceneBtn = new QPushButton("刷新模型",farme);
    m_refreshSceneBtn->setObjectName("scene_manager_btn");
    m_refreshSceneBtn->setStyleSheet("QPushButton { background-color: #1e3050; border: none; border-radius: 6px; color: white;}");
    m_refreshSceneBtn->setIconSize(QSize(25,25));
    m_refreshSceneBtn->setMinimumSize(90, 25);
    m_refreshSceneBtn->setIcon(QIcon(iconsMgr->getPixmap(QColor::fromString("#63E6BE"), IconHelper::FontAwesome6Solid, 0xf2f9, 19, 25,25)));
    connect(m_refreshSceneBtn,&QPushButton::clicked,this,[=](){
        this->reloadAllModel();
    });

    QHBoxLayout* btnLayout = new QHBoxLayout();
    btnLayout->setContentsMargins(0,0,0,40);
    btnLayout->addStretch(1);
    btnLayout->addWidget(m_newSceneBtn);
    btnLayout->addWidget(m_importModelBtn);
    btnLayout->addWidget(m_refreshSceneBtn);
    btnLayout->addStretch(0);

    farme->setLayout(btnLayout);
    farme->setFixedHeight(30);

    m_modelView = new QListView(this);
    m_modelView->setObjectName("scene_manager_view");
    m_modelView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_modelView->setViewMode(QListView::IconMode);
    m_modelView->setFlow(QListView::LeftToRight);
    m_modelView->setResizeMode(QListView::Adjust);
    m_modelView->setAcceptDrops(false);
    m_modelView->setDragEnabled(true);
    m_modelView->setSpacing(3);
    m_modelView->setMouseTracking(true);
    m_modelView->setSelectionMode(QAbstractItemView::NoSelection);
    m_modelView->verticalScrollBar()->setSingleStep(20);
    m_modelView->verticalScrollBar()->setObjectName("scene_manager_view_vsb");

    m_model = new QStandardItemModel(m_modelView);
    m_modelView->setModel(m_model);
    m_delegate = new UiModelManageDelegate(m_modelView);
    m_modelView->setItemDelegate(m_delegate);

    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->addWidget(farme);
    //m_mainLayout->addWidget(line);
    m_mainLayout->addWidget(m_modelView);

    connect(m_modelView, &QListView::clicked, this, [&](const QModelIndex &index){
        IconHelper* iconsMgr = IconHelper::instance();

        QStandardItem* item = m_model->item(index.row(), index.column());
        if(nullptr == item)
            return;

        QRect itemRect = m_modelView->visualRect(index);
        if (itemRect.isNull())
            return;
        QRect btnRect = QRect(itemRect.x()+10, itemRect.y()+10, 20, 20);

        QPoint clickpos = m_modelView->mapFromGlobal(QCursor::pos());
        if(clickpos.x() < btnRect.x() || clickpos.x() > btnRect.x()+20 || clickpos.y() < btnRect.y() || clickpos.y() > btnRect.y()+20)
            return;

        QPoint globalRect = m_modelView->mapToGlobal(QPoint(itemRect.x(), itemRect.y()));

        QMenu menu(m_modelView); // 假设m_modelView是QWidget或其子类的实例，用作菜单的父对象

        // 为菜单添加三个菜单项
        QAction *actionedit = menu.addAction("编辑");
        actionedit->setIcon(QIcon(iconsMgr->getPixmap(QColor::fromString("#63E6BE"), IconHelper::FontAwesome6Solid, 0xf044, 15, 15,15)));
        QAction *actionCopy = menu.addAction("复制");
        actionCopy->setIcon(QIcon(iconsMgr->getPixmap(QColor::fromString("#63E6BE"), IconHelper::FontAwesome6Solid, 0xf0c5, 15, 15,15)));
        QAction *actionDelete = menu.addAction("删除");
        actionDelete->setIcon(QIcon(iconsMgr->getPixmap(QColor::fromString("#63E6BE"), IconHelper::FontAwesome6Solid, 0xf2ed, 15, 15,15)));
        QAction *actionLook = menu.addAction("查看");
        actionLook->setIcon(QIcon(iconsMgr->getPixmap(QColor::fromString("#63E6BE"), IconHelper::FontAwesome6Solid, 0xf06e, 15, 15,15)));

        // 阻塞地弹出菜单，等待用户选择
        QAction *selectedAction = menu.exec(QPoint(globalRect.x()+30, globalRect.y()+10)); // 在项的全局位置弹出菜单
        if(!selectedAction)
            return;

        // 检查用户的选择
        if (selectedAction == actionedit) {
            UiModelInfo* window = new UiModelInfo();
            window->setObjectName(windowNameMap.value(EWindowType::EditModel));
            bool exists = false;
            // CSigMgr.sigFindExistsWidget(EWindowType::EditModel, exists);

            // exists ? CSigMgr.sigDelWidget(EWindowType::EditModel, EWindowType::EditModel, window)
            //        : CSigMgr.sigAddWidget(window, EWindowType::EditModel);
        } else if (selectedAction == actionCopy) {
            qDebug() << "用户选择了选项 2";
            // 执行相关操作
        } else if (selectedAction == actionDelete) {
            qDebug() << "用户选择了选项 3";
            // 执行相关操作
        } else if (selectedAction == actionLook) {
            qDebug() << "用户选择了选项 3";
            // 执行相关操作
        }
    });

    reloadAllModel();
}

void UiModelManage::initData()
{

}

void UiModelManage::reloadAllModel() {
    m_model->clear();
    m_modelDataMap.clear();

#if TEST_MODEL_MANAGE
    QList<QSharedPointer<CModelInfo>> modelList;
    if(!CWebRequestApi::ins().getModelList(modelList))
        return;

    // for(auto &info : modelList) {
    //     m_modelDataMap.insert(info->getFieldValueByFielddName(modelColFieldsNameMap.value(CModelInfo::EModelCol::EModelName)).toString(), info);
    //     QStandardItem* item = new QStandardItem();
    //     item->setData(info->getFieldValueByFielddName(modelColFieldsNameMap.value(CModelInfo::EModelCol::EModelName)),Qt::DisplayRole);
    //     item->setData(QVariant::fromValue(info),Qt::UserRole);
    //     m_model->appendRow(item);
    // }

#else
    QJsonObject resquestBody;
    for(int i = 0; i < 50; i++) {
        QJsonObject obj;
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelName)] = QString("model%1").arg(i);
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelUser)] = QString("user%1").arg(i);
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelDescr)] = QString("这是模型%1").arg(i);
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelSn)] = i;
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EGroguping)] = QString("分组%1").arg(i);;
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelLocation)] = QString("location%1").arg(i);
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelCreate_time)] = QDateTime::currentDateTime().toString();
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelUpdate_time)] = QDateTime::currentDateTime().toString();
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelProducer)] = QString("producer%1").arg(i);
        obj[modelColToStringMap.value(CModelInfo::EModelCol::EModelValid)] = true;

        QSharedPointer<IModel> info(new CModelInfo);
        info->fromJson(obj);
        m_modelDataMap.insert(info->getFieldValueByFielddName(modelColFieldsNameMap.value(CModelInfo::EModelCol::EModelName)).toString(), info);

        QStandardItem* item = new QStandardItem();
        item->setData(info->getFieldValueByFielddName(modelColFieldsNameMap.value(CModelInfo::EModelCol::EModelName)),Qt::DisplayRole);
        item->setData(QVariant::fromValue(info),Qt::UserRole);

        m_model->appendRow(item);
    }
#endif
}

bool UiModelManage::eventFilter(QObject *obj, QEvent *event)
{

}

void UiModelManage::paintEvent(QPaintEvent *event)
{

}


